package com.dnzx.base;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

public class ApiRequestWarpper extends HttpServletRequestWrapper {

    private JSONObject data;

    public ApiRequestWarpper(ServletRequest request) {
        super((HttpServletRequest) request);
        try {
            String dataEn = HttpRequestUtils.readContentFormRequest((HttpServletRequest) request);
            if (StringUtils.isNotEmpty(dataEn)) {
                data = JSONObject.parseObject(AESOperator.getInstance().decrypt(dataEn));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String[] getParameterValues(String name) {
        if (data == null) {
            return null;
        }
        String[] result = new String[1];
        if (data.containsKey(name)) {
            result[0] = data.getString(name);
            return result;
        }
        return null;
    }

    @Override
    public String getParameter(String name) {
        return super.getParameter(name);
    }

    @Override
    public Map getParameterMap() {
        return super.getParameterMap();
    }

    @Override
    public Enumeration getParameterNames() {
        return new Itermeration(data.keySet().iterator());
    }

    public static class Itermeration implements Enumeration<String> {

        Iterator<String> it;

        public Itermeration(Iterator<String> it) {
            this.it = it;
        }

        public boolean hasMoreElements() {
            return it.hasNext();
        }

        public String nextElement() {
            return it.next();
        }
    }
}
